"""
FastAPI应用主入口
"""

from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware
from fastapi.responses import JSONResponse
import uvicorn
import logging
from contextlib import asynccontextmanager

from .core.config import settings
from .core.logging import setup_logging
from .core.exceptions import setup_exception_handlers
from .api.v1 import api_router
from .core.database import init_db
from .services.tts import tts_service


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    # 启动时执行
    setup_logging()
    logging.info("Starting Offline Language Player API...")
    
    # 初始化数据库 - 通过clean_start.py已经完成，这里只是记录日志
    from .core.database import engine, async_session_factory
    if engine and async_session_factory:
        logging.info("Database already initialized by startup script")
    else:
        try:
            await init_db()
            logging.info("Database initialized successfully")
        except Exception as e:
            logging.error(f"Failed to initialize database: {e}")
    
    # 初始化TTS服务
    try:
        await tts_service.initialize()
        logging.info("TTS service initialized successfully")
    except Exception as e:
        logging.error(f"Failed to initialize TTS service: {e}")
    
    yield
    
    # 关闭时执行
    logging.info("Shutting down Offline Language Player API...")
    
    # 清理TTS服务
    try:
        await tts_service.cleanup()
        logging.info("TTS service cleaned up")
    except Exception as e:
        logging.error(f"Failed to cleanup TTS service: {e}")


def create_app() -> FastAPI:
    """创建FastAPI应用实例"""
    
    # 创建FastAPI应用
    app = FastAPI(
        title=settings.PROJECT_NAME,
        description=settings.PROJECT_DESCRIPTION,
        version=settings.VERSION,
        openapi_url=f"{settings.API_V1_STR}/openapi.json",
        docs_url=f"{settings.API_V1_STR}/docs",
        redoc_url=f"{settings.API_V1_STR}/redoc",
        lifespan=lifespan
    )
    
    # 配置CORS
    if settings.BACKEND_CORS_ORIGINS:
        app.add_middleware(
            CORSMiddleware,
            allow_origins=[str(origin) for origin in settings.BACKEND_CORS_ORIGINS],
            allow_credentials=True,
            allow_methods=["*"],
            allow_headers=["*"],
        )
    
    # 配置可信主机
    if settings.ALLOWED_HOSTS:
        app.add_middleware(
            TrustedHostMiddleware,
            allowed_hosts=settings.ALLOWED_HOSTS
        )
    
    # 设置异常处理器
    setup_exception_handlers(app)
    
    # 注册路由
    app.include_router(api_router, prefix=settings.API_V1_STR)
    
    # 健康检查端点
    @app.get("/health")
    async def health_check():
        """健康检查"""
        return {
            "status": "healthy",
            "version": settings.VERSION,
            "service": settings.PROJECT_NAME
        }
    
    # 根路径
    @app.get("/")
    async def root():
        """根路径"""
        return {
            "message": f"Welcome to {settings.PROJECT_NAME}",
            "version": settings.VERSION,
            "docs": f"{settings.API_V1_STR}/docs"
        }
    
    return app


# 创建应用实例
app = create_app()


def main():
    """主函数"""
    uvicorn.run(
        "app.main:app",
        host=settings.HOST,
        port=settings.PORT,
        reload=settings.DEBUG,
        log_level="info" if not settings.DEBUG else "debug"
    )


if __name__ == "__main__":
    main()
